package com.lys.service.impl;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lys.service.WeatherDataService;
import com.lys.vo.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class IWeatherDataService implements WeatherDataService {
    private final static Logger logger= LoggerFactory.getLogger(IWeatherDataService.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public WeatherResponse getDataByCityKey(String cityId) {
        return this.doGetWeahter(cityId);
    }
    private WeatherResponse doGetWeahter(String key) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        WeatherResponse resp = null;
        String strBody = null;
        //先查缓存 再查服务
        if(stringRedisTemplate.hasKey(key)){//是否有缓存！
            logger.info("redis has data ++++++++++++++");
            strBody=ops.get(key);
        }else{
            logger.info("redis no data  ++++++++++++++");
            throw new RuntimeException("redis no data");
        }
        try {
            resp = mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            logger.error("exception",e);
        }

        return resp;
    }
}
